import { Form, Input, message, Modal, type FormProps } from "antd";
import { useEffect, useState, useRef } from "react";
import { addBuilding } from "../../apis/building";
import type { AddbuildingParams, paraentDataFace } from "../../type/building";


interface PropsParams {
    openAddChild: boolean;
    refreshChild: () => void;
    paraentData: paraentDataFace;
}

type FieldType = {
    id?: number;
    name?: string;
    pid?: number
    paraentName?: string
};

export default function AddChild({ openAddChild, refreshChild, paraentData }: PropsParams) {
    const [isModalOpen, setIsModalOpen] = useState(openAddChild);
    const formRef = useRef<any>(null); // 创建表单引用
    useEffect(() => {
        if (!isModalOpen) {
            // 当模态框关闭时，通知父组件更新状态
            // 这样可以确保下次打开时状态是同步的
            refreshChild();
        }
    }, [isModalOpen]);

    useEffect(() => {
        if (paraentData.id && formRef.current) {
            // 确保在下次渲染时设置表单值
            Promise.resolve().then(() => {
                formRef.current?.setFieldsValue({
                    paraentName: paraentData.name
                });
            });
        }
    }, [paraentData]);

    useEffect(() => {
        setIsModalOpen(openAddChild);
    }, [openAddChild]);

    const handleCancel = () => {
        setIsModalOpen(false);
        formRef.current?.resetFields(); // 清空表单数据
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        Add(values)
    };
    const Add = async (values: FieldType) => {
    values.pid = paraentData.id
    values.id = 0
    let res = await addBuilding(values as AddbuildingParams)
    if (res.errCode == 10000) {
        message.success('添加成功');
        refreshChild()
    } else {
        message.error('添加失败');
    }
    formRef.current?.resetFields(); // 清空表单数据
    setIsModalOpen(false);
}

    const handleOk = () => {
        formRef.current?.submit(); // 触发表单提交
    };

    return (
        <Modal
            title='添加子节点'
            closable={{ 'aria-label': 'Custom Close Button' }}
            open={isModalOpen}
            onOk={handleOk}  // 使用 handleOk 替代 onFinish
            onCancel={handleCancel}
            okText="确认"
            cancelText="取消"
        >
            <Form
                ref={formRef}
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                style={{ maxWidth: 600 }}
                initialValues={{
                    remember: true,
                    paraentName: paraentData.name
                }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="父级楼栋名称"
                    name="paraentName"
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item<FieldType>
                    label="名称"
                    name="name"
                    rules={[{ required: true, message: '请输入小区名称' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    );
}